import { createRouter, createWebHistory } from 'vue-router'
import { message } from 'ant-design-vue'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    component: () => import('@/layout/MainLayout.vue'),
    redirect: '/dashboard',
    meta: { requiresAuth: true },
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: { title: '数据看板', icon: 'DashboardOutlined' }
      },
      {
        path: 'customer',
        name: 'Customer',
        component: () => import('@/views/Customer.vue'),
        meta: { title: '客户管理', icon: 'UserOutlined' }
      },
      {
        path: 'vehicle',
        name: 'Vehicle',
        component: () => import('@/views/Vehicle.vue'),
        meta: { title: '车辆管理', icon: 'CarOutlined' }
      },
      {
        path: 'maintenance',
        name: 'Maintenance',
        component: () => import('@/views/Maintenance.vue'),
        meta: { title: '保养记录', icon: 'ToolOutlined' }
      },
      {
        path: 'repair',
        name: 'Repair',
        component: () => import('@/views/Repair.vue'),
        meta: { title: '维修记录', icon: 'SettingOutlined' }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  
  if (to.meta.requiresAuth !== false) {
    // 需要登录的页面
    if (!token) {
      message.warning('请先登录')
      next('/login')
    } else {
      next()
    }
  } else {
    // 不需要登录的页面（如登录页）
    if (token && to.path === '/login') {
      // 已登录状态访问登录页，跳转到首页
      next('/')
    } else {
      next()
    }
  }
})

export default router

